package com.liit.console.controller.front;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.liit.console.filter.WebContext;
import com.liit.module.entity.Template;
import com.liit.module.frame.utils.ConfigUtil;
import com.liit.module.frame.utils.Const;
import com.liit.module.frame.utils.ValidatorUtils;
import com.liit.module.service.TemplateService;

/**
 * @author dingweibo
 * @Title: AboutUsController.java
 * @Description: 关于我们
 * @date 2016年1月3日
 */
@Controller
@RequestMapping(value = "/aboutUs")
public class AboutUsController {

	private Logger logger = Logger.getLogger(getClass());

	@Resource
	TemplateService templateService;

	@RequestMapping(value = "/add")
	public String add() {
		Template record = templateService.selectById(2);
		WebContext.setAttribute("template", record);
		return "/front/aboutUsAdd";
	}

	@RequestMapping(value = "/save")
	public String save(@RequestParam("imgFile") MultipartFile[] imgFile, Template template) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 上传文件
			String path = ConfigUtil.get("file.upload.path") + Const.UPLOAD_PATH_ABOUTUS;
			for (int i = 0; i < imgFile.length; i++) {
				MultipartFile multipartFile = imgFile[i];
				if (!multipartFile.isEmpty()) {
					File targetFile = new File(path, String.valueOf((i + 1)));
					if (!targetFile.exists()) {
						targetFile.mkdirs();
					}
					multipartFile.transferTo(targetFile);
				}
			}
			String message = ValidatorUtils.validate(template);
			if (StringUtils.isBlank(message)) {
				int i = templateService.updateById(template);
				if (i > 0) {
					WebContext.setAttribute(Const.MSG, "保存成功");
				}
			} else {
				map.put(Const.MSG, message);
			}
		} catch (Exception e) {
			logger.error("", e);
			WebContext.setAttribute(Const.MSG, "保存失败");
		}
		return "/front/aboutUsAdd";
	}
}
